package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.SysConfig;
import com.itheima.ydd.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("/sys_config")
@CrossOrigin
@Slf4j
public class SysConfigController {
    @Autowired
    private ISysConfigService iSysConfigService;


    /**
     * 系统配置all请求
     *
     * @return
     */
    @GetMapping("/all")
    public ResultData all() {
        log.info("------------------------测试all接口");
//        List<Map<String,Object>> list=new ArrayList<>();

        Map<String, Object> configRules = new HashMap<>(); //准备设置configRules

        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<>();
        lqw.select(SysConfig::getValidator);//查询条件
        List<SysConfig> configList = iSysConfigService.list(lqw); //满足条件的集合,准备遍历

        StringBuilder configRuleStr = new StringBuilder();
        for (SysConfig config : configList) {
            String validator = config.getValidator();   //获取查询到的每个对象的validator值
            if (StringUtils.isNotEmpty(validator)) {  //如果不为空
                configRuleStr.append(validator.length() > 0 ? "," + validator : validator); //格式
            }
        }

        configRules.put("site_name", configRuleStr);//configRules搞定

        Map<String, Object> configForm = new HashMap<>();
        List<SysConfig> sysConfigs = iSysConfigService.list(); //获取系统设置表所有对象


        //设置configForm集合
        for (SysConfig config : sysConfigs) {
            String key = config.getAttrKey();
            String value = config.getAttrValue();
            configForm.put(key, value);
        }


        System.out.println("1111");
        //设置list
        List<Map<String, Object>> list = iSysConfigService.getList();

    /*    //设置alldata
        for (SysConfig sysConfig : configList) {
            System.out.println(sysConfig.getId().intValue());
            if (sysConfig.getId()!=null&&sysConfig.getId().intValue() == 125) {
                List<Map<String, Object>> sysConfig125 = iSysConfigService.get125ConfigValue();
                sysConfig.setConfigValue(sysConfig125);
            }
        }
*/

        //用一个map集合封装
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("allData", sysConfigs);
        data.put("configForm", configForm);
        data.put("configRules", configRules);


        return ResultData.ok("", data);
    }


    @PostMapping("/update")
    public ResultData update(@RequestBody List<SysConfig> sysConfig){
        iSysConfigService.updateBatchById(sysConfig);
        return ResultData.ok("修改成功",null);

    }
}
